<template>
  <div>
    <el-row
      justify="center"
      style="
        text-align: center;
        margin-top: 20px;
        display: flex;
        align-items: center;
      "
    >
      <el-col :span="6">
        <el-button
          type="primary"
          icon="el-icon-upload"
          @click="btnUpload"
          :disabled="!checkPermission('Image_management-add')"
          >上传图片</el-button
        >
      </el-col>
      <el-col :span="6" style="transform: translateY(10px)">
        <el-form ref="form" label-width="80px">
          <el-form-item label="直播id:">
            <el-input
              v-model.number="liveId"
              placeholder="请输入直播id"
            ></el-input>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="6">
        <el-button icon="el-icon-search" type="primary" @click="search"
          >搜索</el-button
        >
      </el-col>
      <el-col :span="6">
        <!-- <el-button type="primary" @click="imgBeautify">图片美化</el-button> -->
      </el-col>
      <el-col :span="6">
        <el-button
          type="primary"
          icon="el-icon-position"
          @click="oneClickPush"
          :disabled="!checkPermission('Image_management-push')"
          >一键推送</el-button
        >
      </el-col>
    </el-row>

    <!-- table表格 -->
    <el-row style="margin-top: 20px">
      <el-table
        :data="imgData"
        style="width: 100%"
        stripe
        :header-cell-style="{
          background: '#eef1f6',
          color: '#606266',
          textAlign: 'center',
        }"
        border
      >
        <!-- <el-table-column label="图片id" align="center" prop="id">
        </el-table-column> -->
        <el-table-column label="图片" align="center">
          <template v-slot="{ row }">
            <!-- 使用flex容器来对齐子元素 -->
            <div style="display: flex; justify-content: space-around">
              <div
                v-for="(item, index) in row"
                :key="index"
                class="image-container"
              >
                <!-- 图片 -->
                <img class="img" :src="item.urlSL" alt="" />
                <div
                  class="rotunDityBox"
                  style="
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                  "
                >
                  <!-- 输入框 -->
                  <div class="rotunDity">
                    <input
                      ref="isCheckbox"
                      type="checkbox"
                      id="checkbox1"
                      class="checkboxClss"
                      :disabled="item.status === 1"
                      @change="handleCheckboxChange(item.id)"
                    />
                  </div>

                  <!-- 状态 -->
                  <div class="status" style="width: 50px">
                    {{ item.status === 1 ? "已推送" : "未推送" }}
                  </div>

                  <!-- 按钮 -->
                  <div class="btnButton">
                    <el-popconfirm
                      title="确认操作吗?"
                      @onConfirm="imgBtnDel(item.id)"
                    >
                      <el-button
                        slot="reference"
                        style="color: red; margin-left: 10px"
                        :disabled="!checkPermission('Image_management-del')"
                        >{{
                          item.status === 1 ? "改变状态" : "删除"
                        }}</el-button
                      >
                    </el-popconfirm>
                    <!-- <el-button
                      type="primary"
                      style="margin-left: 10px"
                      @click="$router.push(`/imageUpload/detail/${item.id}`)"
                      :disabled="!checkPermission('Image_management-show')"
                      >详情</el-button
                    > -->
                  </div>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
        ></el-table-column> -->
        <!-- <el-table-column label="图片链接" align="center">
          <template v-slot="{ row }">
            <el-button type="primary" @click="btnOnHD(row.id)"
              >图片高清图</el-button
            >
          </template>
        </el-table-column> -->
        <!-- <el-table-column label="按钮" align="center">
          <template v-slot="{ row }">
            <div class="rotunDity">
              <input
                type="checkbox"
                id="checkbox1"
                class="checkboxClss"
                :disabled="row.status === 1"
                @change="handleCheckboxChange(row.id)"
              />
            </div>
          </template>
        </el-table-column> -->
        <!-- <el-table-column label="状态" align="center">
          <template v-slot="{ row }">
            {{ row.status === 1 ? "已推送" : "未推送" }}
          </template>
        </el-table-column> -->
        <!-- <el-table-column label="操作" align="center">
          <template v-slot="{ row }">
            <el-popconfirm title="确认删除吗?" @onConfirm="imgBtnDel(row.id)">
              <el-button
                slot="reference"
                style="color: red"
                :disabled="!checkPermission('Image_management-del')"
                >删除</el-button
              >
            </el-popconfirm>
            <el-button
              type="primary"
              style="margin-left: 20px"
              @click="$router.push(`/imageUpload/detail/${row.id}`)"
              :disabled="!checkPermission('Image_management-show')"
              >详情</el-button
            >
          </template>
        </el-table-column> -->
      </el-table>
    </el-row>

    <!-- 预览弹层 -->
    <el-dialog :visible.sync="showDialog" title="图片预览">
      <img :src="imgUrl" alt="" style="width: 100%" />
    </el-dialog>

    <!-- 上传图片弹层 -->
    <el-dialog title="上传图片" :visible.sync="imgDialog" @close="close">
      <el-form
        ref="formRef"
        label-width="85px"
        :rules="rules"
        :model="formData"
      >
        <el-form-item label="直播id:" prop="liveId">
          <el-input
            v-model="formData.liveId"
            placeholder="请输入直播id"
          ></el-input>
        </el-form-item>
        <el-form-item label="添加图片:" prop="file">
          <el-upload
            ref="upload"
            list-type="picture-card"
            v-model="formData.file"
            multiple
            action="#"
            :auto-upload="false"
            :on-preview="handlePreview"
            :on-change="handleChange"
            :on-remove="handleRemove"
            :before-upload="beforeUpload"
            :file-list="fileList"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-row type="flex" justify="center">
          <el-col :span="4">
            <el-button size="mini" type="warning" @click="close">取消</el-button>
            <el-button size="mini" type="primary" @click="btnOk">确认</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>

    <!-- 高清图的弹层 -->
    <el-dialog title="高清图" :visible.sync="imgGQDialog">
      <img :src="imgGqUrl" alt="" style="width: 100%; height: 100%" />
    </el-dialog>

    <!-- 输入 -->
    <el-dialog title="直播id" :visible.sync="liveIdDialog">
      <el-form label-width="80px">
        <el-form-item label="直播id:" prop="liveId">
          <el-input
            v-model="liveFormData.liveId"
            placeholder="请输入直播id"
          ></el-input>
        </el-form-item>
        <el-form-item label="">
          <el-row type="flex" justify="center">
            <el-col :span="8">
              <el-button type="primary" @click="btnLiveIdClose">取消</el-button>
              <el-button type="primary" @click="btnLiveIdOk">确认</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 分页组件 -->
    <el-row type="flex" justify="center">
      <el-pagination
        :page-size="pageParams.pagesize"
        :page-sizes="[5, 10, 15, 20, 30, 50, 100]"
        :total="total"
        :current-page="pageParams.page"
        layout="total, sizes, prev, pager, next, jumper"
        @current-change="changePage"
        @size-change="handleSizeChange"
      />
    </el-row>
  </div>
</template>

<script>
import {
  uploadApi,
  getImageListApi,
  deleteImageApi,
  highDefinitionImagesApi,
  oneClickPushApi,
} from "@/api/uploadImage";

import MTImageEditor, { MTImageEditorClass } from "mt-image-editor-sdk";
export default {
  data() {
    return {
      uploadUrl: "",
      fileList: [],
      showDialog: false,
      imgDialog: false,
      imgGQDialog: false,
      imgUrl: "",
      imgGqUrl: "",
      formData: {
        file: [],
        liveId: "",
      },
      liveFormData: {
        liveId: "",
        base64ToFile: "",
      },
      // 存放file的数组
      pictureList: [],
      // 数据对象
      imgData: [],
      total: 0,
      pageParams: {
        page: 1,
        pageSize: 10,
      },
      liveId: "",
      value: false,
      liveIdDialog: false,
      rules: {
        liveId: [{ required: true, message: "请输入直播id", trigger: "blur" }],
        file: [
          { required: true, validator: this.validateImage, trigger: "change" },
        ],
      },
      // 选中id的数组
      ids: [],
    };
  },
  created() {
    // 获取图片列表数据
    this.getImageList();
  },
  mounted() {
    // // 初始化SDK,建议页面一进来执行，提高后续打开速度
    // MTImageEditor.init({
    //   // 使用的SDK名称
    //   moduleName: "image-editor-sdk",
    //   // 必填，到开放平台申请通过后才可用
    //   accessKey: "test_app_key_demo",
    //   title: "美图秀秀Web版",
    //   // 默认以弹窗形式展现，指定el后嵌入到指定target
    //   el: "",
    //   // 初始打开的图片
    //   // 您使用的图片域名，须添加跨域支持 eg: access-control-allow-origin: *
    //   imageSrc:
    //     "https://xiuxiupro-material-center.meitudata.com/poster/a5b124caae6c1f35be58ba7ba651725a.jpg",
    //   //是否带有全屏功能
    //   fullscreen: true,
    //   // 窗体宽高是否跟随window.onresize变更
    //   resizeAble: true,
    // });
  },
  computed: {
    formattedDates() {
      // 格式化日期
      return this.imgData.map((item) => ({
        ...item,
        createTime: this.formatSeconds(item.createTime),
      }));
    },
  },
  methods: {
    // 点击图片美化
    imgBeautify() {
      this.liveIdDialog = true;
    },
    // 点击确认
    btnLiveIdOk() {
      if (this.liveFormData.liveId == "") {
        alert("请输入直播id");
        return;
      }
      this.liveIdDialog = false;
      console.log(this.liveFormData.liveId);
      // this.liveFormData.liveId = "";
      this.openImageEditor();
    },
    openImageEditor() {
      // 初始化SDK,建议页面一进来执行，提高后续打开速度
      MTImageEditor.init({
        // 使用的SDK名称
        moduleName: "image-editor-sdk",

        // 必填，到开放平台申请通过后才可用
        accessKey: "test_app_key_demo",

        title: "美图秀秀Web版",

        // 默认以弹窗形式展现，指定el后嵌入到指定target
        el: "",

        // 初始打开的图片
        // 您使用的图片域名，须添加跨域支持 eg: access-control-allow-origin: *
        imageSrc:
          "https://xiuxiupro-material-center.meitudata.com/poster/a5b124caae6c1f35be58ba7ba651725a.jpg",

        //是否带有全屏功能
        fullscreen: true,

        // 窗体宽高是否跟随window.onresize变更
        resizeAble: true,
      });
      // 保存回调
      MTImageEditor.saveImage(async (base64, type, id) => {
        // base64：图片数据
        // type：图片类型,jpg|png
        // id：作图记录id //可用于二次编辑
        this.liveFormData.base64ToFile = base64;
        // console.log(this.liveFormData.base64ToFile);
        // console.log(this.liveFormData);
        try {
          // const formData=new FormData();
          // formData.append('liveId',this.liveFormData.liveId)
          // formData.append('base64ToFile',this.liveFormData.base64ToFile)
          const res = await uploadApi(this.liveFormData);
          console.log(res);
          if (res.code === 1) {
            console.log("操作成功");
            console.log(this);
            this.$message.success("操作成功");
            // alert('操作成功!')
          }
        } catch (error) {
          console.log(error);
        }
        // console.log(res);
      });
      //关闭弹窗
      // MTImageEditor.close();

      //监听弹窗关闭
      MTImageEditor.onClose(() => {
        console.log("弹窗关闭");
      });
    },
    // 点击取消
    btnLiveIdClose() {
      this.liveIdDialog = false;
      this.liveFormData.liveId = "";
    },
    // 封装一个转化时间的函数
    formatSeconds(seconds) {
      // 将秒数转化为日期格式
      const date = new Date(seconds);
      return date.toLocaleString();
    },
    // 自定义图片校验
    validateImage(rule, value, callback) {
      // console.log(this.fileList);
      // console.log(this.formData.file);
      // 自定义图片校验逻辑
      const isValid = this.fileList.length > 0; // 校验是否有文件被选中
      // console.log(this.fileList);
      // console.log(isValid);
      if (!isValid) {
        callback(new Error("必须上传图片"));
      } else {
        callback();
      }
    },
    // 点击图片高清图
    async btnOnHD(id) {
      const res = await highDefinitionImagesApi(id);
      this.imgGQDialog = true;
      this.imgGqUrl = res.data;
    },

    // 删除图片
    async imgBtnDel(id) {
      const res = await deleteImageApi(id);
      if (res.code === 1) {
        this.$message.success("操作成功");
        // 重新获取数据
        this.getImageList();
      }
      // 如果当前页面只有一条数据了，页码自减之后在去请求接口，不能是第一页，第一页的页码已经是1了
      if (this.imgData.length === 1 && this.pageParams.page !== 1) {
        this.pageParams.page--;
        // 删除成功之后，进行提示
        this.$message.success("操作成功");
        // 重新获取数据
        this.getImageList();
      }
    },

    // 预览图片
    handlePreview(file) {
      this.imgUrl = file.url;
      this.showDialog = true;
    },
    handleRemove() {},
    beforeRemove() {},
    handleProgress() {},
    handleChange(file, fileList) {
      this.pictureList.push(file.raw);
      console.log(fileList);
      this.fileList = fileList.map((item) => item);
    },
    // 上传图片前的校验判断
    beforeUpload(file) {
      console.log(file);
      // 先检查文件类型
      const types = ["image/jpeg", "image/gif", "image/bmp", "image/png"];
      if (!types.some((item) => item === file.type)) {
        // 如果不存在
        this.$message.error("上传图片只能是 JPG、GIF、BMP、PNG 格式!");
        return false;
      }
      // 检查文件的大小
      // const maxSize = 5 * 1024 * 1024;
      // if (file.size > maxSize) {
      //   // 如果不存在
      //   this.$message.error("上传图片大小不能超过 5MB!");
      //   return false;
      // }
      // return true;
    },
    // 清空表单
    close() {
      // 重置表单数据
      // 关闭弹层
      this.imgDialog = false;
      this.formData.liveId = "";
      this.fileList = [];
      this.$refs.formRef.resetFields();
    },

    // 点击上传图片
    btnUpload() {
      this.imgDialog = true;
    },

    // 列表渲染
    async getImageList() {
      const res = await getImageListApi(this.pageParams);
      // console.log(res);
      this.imgData = res.records;
      console.log(this.imgData);
      // console.log(this.imgData.length*5)
      const totalList = this.imgData.length * 5;
      console.log(totalList);
      this.total = res.total;
      console.log(this.total);
      // this.total = res.data.total;
    },

    // 点击了分页组件的页码的时候
    changePage(page) {
      this.pageParams.page = page;
      // 重新获取列表数据
      this.getImageList();
    },

    // 每页显示的条数发生改变
    handleSizeChange(val) {
      this.pageParams.pageSize = val;
      // 重新获取列表数据
      this.getImageList();
    },

    // 确认上传
    async btnOk() {
      try {
        // 校验表单
        await this.$refs.formRef.validate();
        // 循环依次上传
        this.pictureList.forEach((item) => {
          const uploadForm = new FormData();
          uploadForm.append("file", item);
          uploadForm.append("liveId", this.formData.liveId);
          // await uploadApi
          uploadApi(uploadForm).then((res) => {
            if (res.code === 1) {
              this.fileList = [];
              this.pictureList = [];
              this.$message.success("上传成功");
              // 重新获取数据
              this.getImageList();
            }
          });
        });
        // console.log(res);
        // 关闭弹层
        this.imgDialog = false;
      } catch {
        this.$message.error("表单校验失败");
        return false;
      }
    },

    // 一键推送
    async oneClickPush() {
      const res = await oneClickPushApi(this.ids);
      if (res.code === 1) {
        this.$message.success("推送成功");
        this.getImageList();
      }
    },

    // 点击勾选框获取图片id
    handleCheckboxChange(id) {
      const index = this.ids.indexOf(id);
      if (index !== -1) {
        this.ids.splice(index, 1); // 如果已经存在则移除
      } else {
        this.ids.push(id); // 否则添加
      }
      // console.log(this.ids);
    },
    // 点击搜索
    search() {
      // 增加一个属性
      this.$set(this.pageParams, "liveId", this.liveId);
      // 重新渲染
      this.getImageList();
      this.liveId = "";
    },
  },
};
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
/* ::v-deep .el-upload-list {
  display: none !important;
} */
/* .disabled .el-upload el-upload--picture-card {
  display: none;
} */
.img {
  width: 250px;
  height: 200px;
}
.rotunDity {
  width: 40px;
  height: 40px;
}
/* .image-container { */
/* 确保每个图片容器不换行 */
/* flex: 1; */
/* 图片之间的间距，可以根据需要调整 */
/* margin: 0 5px; */
/* } */

/* .checkboxClss {
  width: 25px;
  height: 25px;
} */
.checkboxClss {
  width: 100%;
  height: 100%;
}
</style>
